﻿using AutoMapper;
using MediatR;
using Provenance.Domain.User;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Write.Api.Application.Command.User;

namespace Provenance.Write.Api.Application.CommandHandler.User
{
    public class InsertPermissionCommandHandler : IRequestHandler<InsertPermissionCommand, ApiResult>
    {
        private readonly IPermissionRepository _permissionRepository;
        private readonly ILogger<InsertPermissionCommandHandler> _logger;
        private readonly IMapper _mapper;
        public InsertPermissionCommandHandler(IPermissionRepository permissionRepository, ILogger<InsertPermissionCommandHandler> logger, IMapper mapper)
        {
            _permissionRepository = permissionRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(InsertPermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = _mapper.Map<Permission>(request);
                await _permissionRepository.InsertEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error inserting permission" + ex.Message);
                return ApiResult.Failure("Error inserting permission" + ex.Message);
            }
        }
    }
}
